$(function () {
    var details = $("#details"),
        uuid = 0,
        rsvps = [],
        memIds = [],
        cleanupInterval = 2000,
        stop = true,
        unlim = false,
        detailShow, msg, tOut, cleanup = function () {
            var expiry = 1000 * 60 * 2,
                cutoff = new Date() - expiry;
            var i = 0;
            while (i < rsvps.length && rsvps[i].time < cutoff) {
                i++
            }
            if (i > 0) {
                rsvps.splice(0, i)
            }
        };
    setInterval(cleanup, cleanupInterval);
    var updateTimes = function () {
            $(".rsvp .time").each(function () {
                var elem = $(this);
                elem.text(mu.Time.ago(elem.attr("mtime")))
            })
        };
    setInterval(updateTimes, 1000);
    var getMsg = function (rsvp, showTime) {
            var now = new Date();
            rsvp.systime = now.getTime();
            var imgCode = "";
            if (rsvp.member.photo != undefined) {
                imgCode = '<img src="' + rsvp.member.photo + '" />'
            }
            var groupurl = rsvp.group.group_urlname;
            if (groupurl.substr(0, 1) == "+") {
                var urlarray = groupurl.split(":");
                if (urlarray.length > 1) {
                    groupurl = urlarray[0].substr(1, groupurl.length);
                    groupurl = "http://" + groupurl
                }
            } else {
                groupurl = "/" + groupurl
            }
            var out = ['<div class="rsvp omnCamp omngj_sj50" data-url="' + groupurl + '"><span class="member-photo">', imgCode, '</span><div class="member-info"><div class="rsvp-head"><span class="member">', escapeHtml(rsvp.member.member_name), "</span>", (showTime ? ' <span class="time" mtime="' + rsvp.systime + '">' + mu.Time.ago(rsvp.systime) + "</span>" : '<span class="static-time">Today</span>'), "</div>", '<div class="rsvp-body">is attending a Meetup with <span class="group"><a href="', groupurl, '" class="omnCamp omngj_sj50">', escapeHtml(rsvp.group.group_name), '</a></span> in <span class="place">', rsvp.group.group_city, ", ", (rsvp.group.group_state ? rsvp.group.group_state : rsvp.group.group_country).toUpperCase(), "</span></div>", "</div></div>"].join("");
            return out
        };
    var escapeHtml = function (html) {
            return html.replace(/</g, "&lt;").replace(/>/g, "&gt;")
        };
    var addToFlow = function (msg, isReal) {
            if (isReal) {
                rsvps.push({
                    id: "r-" + uuid++,
                    time: +new Date()
                })
            }
            var depth = Math.min(rsvps.length, 60);
            if (depth > 2) {
                var rate = (depth - 1) * 60 * 1000 / (rsvps[rsvps.length - 1].time - rsvps[rsvps.length - depth].time)
            }
            var details = $("#rsvpStream"),
                detail = $(msg).hide(),
                showDetail = function () {
                    if (!stop) {
                        var maxrsvps = 12;
                        details.prepend(detail);
                        detail.css({
                            opacity: 0
                        }).animate({
                            height: "toggle",
                            opacity: 1
                        }, 500, function () {
                            details.children().each(function (idx) {
                                if (idx > maxrsvps) {
                                    $(this).remove();
                                    memIds.splice(0, 1)
                                }
                            });
                            details = null
                        })
                    }
                };
            detailShow = setTimeout(showDetail, 500);
            return 1
        };
    var mu = mu || {};
    raw = $("<div/>").html(raw).text();
    raw = raw.substring(1, raw.length - 1);
    var obj = jQuery.parseJSON(raw);
    var i = 15;
    var addAnother = function () {
            if (i < obj.length) {
                addToFlow(getMsg(obj[i], false), false);
                i++
            } else {
                i = 0
            }
        };
    addAnother();
    var dummyAdd = setInterval(addAnother, 1000);
    mu.Time = {
        ago: function (millis) {
            var duration = new Date() - millis;
            if (duration < 1000) {
                return "Just now"
            }
            return this.millisToWords(duration) + " ago"
        },
        millisToWords: function (millis) {
            var print = function (value, name) {
                    var whole = Math.floor(value);
                    return "" + whole + " " + name + ((whole > 1) ? "s" : "")
                };
            var seconds = millis / 1000;
            if (seconds < 60) {
                return print(seconds, "second")
            }
            var minutes = seconds / 60;
            if (minutes < 60) {
                return print(minutes, "minute")
            }
            var hours = minutes / 60;
            if (hours < 24) {
                return print(hours, "hour")
            }
            var days = hours / 24;
            return print(days, "day")
        }
    };
    var numInitStream = 0;
    var stream = function (config) {
            numInitStream++;
            var thisStream = numInitStream;
            var $ = jQuery;
            var url = config.url || "http://stream.meetup.com/2/rsvps",
                wsUrl = config.wsUrl || url.replace(/^http/, "ws"),
                log = config.log ||
            function (msg) {}, error = function (msg) {
                alert(msg)
            }, handleJson = function (json) {
                if (typeof config.callback === "function") {
                    config.callback(json)
                } else {
                    error("callback is not a function")
                }
            }, supportsWebsockets = function () {
                return window.WebSocket || window.MozWebSocket
            };
            if (supportsWebsockets()) {
                var s = window.WebSocket ? new WebSocket(wsUrl) : new MozWebSocket(wsUrl);
                s.onmessage = function (e) {
                    if (stop || (thisStream != numInitStream)) {
                        s.close();
                        return
                    }
                    log(e);
                    handleJson(JSON.parse(e.data))
                }
            } else {
                var newest = 0;
                var successCallback = function (ary) {
                        if (stop || (thisStream != numInitStream)) {
                            return
                        }
                        if (ary) {
                            $.each(ary, function () {
                                handleJson(this);
                                newest = Math.max(newest, this.mtime)
                            })
                        }
                        var params = {};
                        if (newest > 0) {
                            params = {
                                since_mtime: newest
                            }
                        }
                        $.ajax({
                            url: url,
                            data: params,
                            dataType: "jsonp",
                            scriptCharset: "UTF-8",
                            success: successCallback
                        })
                    };
                successCallback()
            }
        };
    var stopStream = function () {
            var toggle = $('<div id="rsvpStream-pause" class="rsvp pause"> Paused<br><input type="button" value="Resume" class="D_submit" /></div>');
            if (stop == false) {
                stop = true;
                clearTimeout(tOut);
                clearTimeout(detailShow);
                clearInterval(dummyAdd);
                rsvps = [];
                $("#r").empty();
                toggle.click(toggleStream);
                $("#rsvpStream").prepend(toggle)
            }
        };
    var startStream = function () {
            $("#rsvpStream").click(function (e) {
                var $target = $(e.target);
                if ($target.hasClass("rsvp")) {
                    var rsvpurl = $target.data("url")
                } else {
                    if ($target.parents().hasClass("rsvp")) {
                        var rsvpurl = $target.parents("div.rsvp").data("url")
                    }
                }
                if (rsvpurl !== undefined) {
                    window.location = rsvpurl
                }
            });
            if (stop == true) {
                if (!(window.location.hash == "#unlimited")) {
                    tOut = setTimeout(stopStream, (1000 * 60 * 5))
                }
                stop = false;
                if (useStream) {
                    stream({
                        url: "http://stream.meetup.com/2/rsvps",
                        callback: function (rsvp) {
                            if (rsvp.response === "yes") {
                                var unique = true;
                                for (m in memIds) {
                                    if ((rsvp.member.member_id == memIds[m].mem) && (rsvp.event.event_id == memIds[m].ev)) {
                                        unique = false
                                    }
                                }
                                if (unique) {
                                    msg = getMsg(rsvp, true);
                                    addToFlow(msg, true);
                                    memIds.push({
                                        mem: rsvp.member.member_id,
                                        ev: rsvp.event.event_id
                                    });
                                    clearInterval(dummyAdd)
                                }
                            }
                            if ((window.location.hash == "#unlimited")) {
                                clearTimeout(tOut)
                            }
                        }
                    })
                }
            }
        };
    var toggleStream = function () {
            if (stop !== false) {
                $("#rsvpStream-pause").slideUp("slow", function () {
                    $(this).remove()
                });
                dummyAdd = setInterval(addAnother, 1000);
                startStream()
            } else {
                stopStream()
            }
        };
    startStream();
    $("input.J_textInputTip").TextInputTip({
        dontStop: true
    })
});